<?php 
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\User;

class AuthController extends AbstractActionController{
    protected $storage; 
    protected $authservice; 
     
    public function getAuthService(){
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()->get('AuthService');
        }
        return $this->authservice;
    }
    
    public function getSessionStorage(){ 
       if (! $this->storage) {
          $this->storage = $this->getServiceLocator()->get('Application\Model\MyAuthStorage');
       }
       return $this->storage;
    } 
    
    public function loginAction(){
       $redirect = array('controller' => 'auth','action' => 'success');
        if ($this->getAuthService()->hasIdentity()){
            return $this->redirect()->toRoute('application',$redirect); 
        }
        return array('messages'  => $this->flashmessenger()->getMessages()); 
    }
     
    public function authenticateAction(){
        $redirect = array('controller' => 'auth','action' => 'login'); 
        $request = $this->getRequest();
        if ($request->isPost()){
           $username = $request->getPost('username'); 
           $password = $request->getPost('password');
           $this->getAuthService()->getAdapter()
                           ->setIdentity($username) 
                           ->setCredential($password); 

                                        
         $result = $this->getAuthService()->authenticate();
         foreach($result->getMessages() as $message){
            $this->flashmessenger()->addMessage($message);
         }
         
         if ($result->isValid()) {
            if ($request->getPost('remember') == '1' ) { 
               $this->getSessionStorage()->setRememberMe(1);
               $this->getAuthService()->setStorage($this->getSessionStorage());
            }
            $redirect = array('controller' => 'auth','action' => 'success'); 
            $this->getAuthService()->getStorage()->write($username);
         }
      }
      return $this->redirect()->toRoute('application',$redirect); 
    }
     
    public function logoutAction(){
       $this->getSessionStorage()->forgetMe();
        $this->getAuthService()->clearIdentity();
         
        $this->flashmessenger()->addMessage("Bạn vừa thoát khỏi hệ thống.");
        return $this->redirect()->toRoute('application',array('controller'=>'auth','action'=>'login'));
    }
    public function successAction(){
       if (! $this->getServiceLocator()->get('AuthService')->hasIdentity()){ 
          return $this->redirect()->toRoute('application',array('controller'=>'auth','action'=>'login')); 
       }
    }
}